from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.core.cache import cache
# Create your models here.


class SponsorType(models.Model):
    """ Indicates the type of sponsorship.
    For example, Diamon, Media, Silver, etc...
    """

    name = models.CharField(max_length=180, unique=True, null=False,
                    blank=False, help_text=_(\
                    "The name of the type of sponsor."))
    importance = models.IntegerField(unique=True, help_text=_(\
                    "The importance of this type."))

    class Meta:
        ordering = ('importance',)


class Organization(models.Model):
    """Organization which might become a sponsor or vendor.

    These can be potential sponsors we are trying to contact, or those
    who have signed up via an online form. Once an invoice is attached, they
    are official.
    """
    name = models.CharField(max_length=180, unique=True, null=False, 
                blank=False)
    #level       = models.ForeignKey(Level)
    small = models.BooleanField(help_text=_("Small Company"))
    nonprofit = models.BooleanField(help_text=_("Non-Profit Organization"))
    created = models.DateTimeField(auto_now_add=True)
    video = models.IntegerField(default=0, help_text=_(\
                               'number of videos which should be sponsored.'))
    PO = models.IntegerField(blank=True, null=True)
    addr1 = models.CharField(max_length=180, blank=True)
    addr2 = models.CharField(max_length=180, blank=True)
    addr3 = models.CharField(max_length=180, blank=True)
    addr4 = models.CharField(max_length=180, blank=True)
    addr5 = models.CharField(max_length=180, blank=True)
    notes = models.TextField(blank=True)

    class Admin:
        list_display  = ('name', 'created', 'PO', 'video')
        search_fields = ('name', 'addr1', 'addr3', 'addr4', 'addr5', 'notes')

    class Meta:
        ordering = ('name',)

    def __unicode__(self):
        return self.name


class ContactType(models.Model):
    """List of contact types which many of which can be set on a single Contact
    Examples:
        Primary
        Billing
        CompReg
        CompVend
    """
    name = models.CharField(max_length=180)

    class Admin:
        pass

    class Meta:
        ordering = ('name',)

    def __unicode__(self):
        return self.name


class Contact(models.Model):
    """Sponsorship or Vendor Contact

    Might be tied to a django login.
    The comp registrations should be listed as contacts as well.
    """
    name  = models.CharField(max_length=180)
    email = models.EmailField(max_length=180)
    # PhoneNumberField default to US phone validation! >.<
    phone = models.CharField(max_length=180)
    notes = models.TextField(blank=True)
    user  = models.ForeignKey(User, blank=True, null=True)
    organization = models.ForeignKey(Organization, null=True, blank=True)
    types = models.ManyToManyField(ContactType, blank=True, null=True)
    primary_type = models.ForeignKey(ContactType, 
                                    verbose_name=_('primary type'), 
                                    related_name='filter_set')

    class Admin:
        list_display  = ('name', 'email', 'phone', 'ptype', 'organization')
        list_filter   = ('ptype', 'organization')
        search_fields = ('name', 'e-mail', 'phone', 'notes', 'organization')

    class Meta:
        ordering = ('name',)

    def __unicode__(self):
        return self.name

    def save(self):
        if self.user and isinstance(self.user, User):
            self.name = unicode(self.user)
            self.email = unicode(self.user.email)
            if self.user.groups.filter(name='Sponsors').count() == 0:
                sg = Group.objects.get(name='Sponsors')
                self.user.groups.add(sg)
                self.user.save()
        return super(Contact, self).save()


class WebsiteLogo(models.Model):
    organization = models.ForeignKey(Organization, null=True, blank=True)
    name     = models.CharField(max_length=180)
    level    = models.ForeignKey(SponsorType)
    index    = models.IntegerField(default=0,
                help_text=_('override sorting order within level. '
                            'sorted by level, index, time added.'))
    added    = models.DateTimeField(auto_now_add=True)
    logo     = models.ImageField(upload_to='TODO')
    url      = models.URLField()
    alt      = models.CharField(max_length=180, blank=True,
                help_text=_('hover alt text. will use name if not provided.'))
    visible  = models.BooleanField()
    contacts = models.ManyToManyField(Contact, null=True, blank=True)

    def get_absolute_url(self):
        return self.get_logo_url() # view on site

    def get_alt(self):
        if self.alt:
            return self.alt
        return self.name

    def save(self):
        # RED_FLAG: Hack! set in website template!
        res = super(WebsiteLogo, self).save()
        try:
            cache.delete('sponsor_logos')
        except:
            pass
        return res

    def __unicode__(self):
        return self.name

    class Admin:
        list_filter  = ('level', 'visible', 'added')
        list_display = ('name', 'organization', 'alt', 'level', \
                        'added', 'visible')

    class Meta:
        ordering = ('level', 'index', 'added', 'name')
